package com.ruipeng.shengyapo.controller;

import com.ruipeng.shengyapo.service.AuthService;
import com.ruipeng.shengyapo.service.CouponService;
import com.ruipeng.shengyapo.service.UserService;
import com.ruipeng.shengyapo.utils.HttpUtils;
import com.ruipeng.shengyapo.utils.ObjUtils;
import com.ruipeng.shengyapo.utils.SendValidataCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by tu_pei on 17/5/27.
 * 短信下发
 */
@Controller
@RequestMapping("sms")
public class SMSController {

	@Autowired
	private UserService userService;

	@Autowired
	private AuthService authService;

	@Autowired
	private CouponService complaintService;
    /**
     * 发送短信验证码
     * url/sms/{userTel}
     * @param userTel 手机号
     * @return
     */
    @RequestMapping(value = "/{userTel}" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> sendPhoneCode(@PathVariable("userTel") String userTel){
		String phoneCode = SendValidataCode.generatorNumber(4);
		if( SendValidataCode.sendSms(userTel, phoneCode)){
			System.out.println("手机号【"+ userTel +"】的验证码是：【"+ phoneCode +"】");
			Map<String,Object> userMap = userService.getByUserTel(userTel);
			if( userMap == null ){
				authService.userRegister(userTel,phoneCode);

				userMap = userService.getByUserTel(userTel);
				//赠送优惠券
				Map<String,Object> params = new HashMap<String,Object>();
				String orderNo = ObjUtils.randomNumeric(10);
				params.put("couponNo","SYB"+orderNo);
				params.put("couponName","晟雅铂单车骑行券");
				params.put("userId",userMap.get("userId"));
				params.put("userTel",userMap.get("userTel"));
				params.put("couponMoney",1);
				complaintService.addComplaint(params);

				params.clear();
				params = new HashMap<String,Object>();
				orderNo = ObjUtils.randomNumeric(10);
				params.put("couponNo","SYB"+orderNo);
				params.put("couponName","晟雅铂单车骑行券");
				params.put("userId",userMap.get("userId"));
				params.put("userTel",userMap.get("userTel"));
				params.put("couponMoney",1);
				complaintService.addComplaint(params);

			}else{
				Map<String,Object> updateMap = new HashMap<String,Object>();
				updateMap.put("userId",userMap.get("userId"));
				updateMap.put("phoneCode",phoneCode);
				userService.updateUserInfo(updateMap);
			}
			return HttpUtils.buildResponseBody4Map(HttpUtils.STATE_TRUE);
		}else{
			return HttpUtils.buildResponseBody4Map(HttpUtils.STATE_FALSE, "短息通道异常");
		}
    }

}
